/**
 * @Date 14-11-2013
 * Class used to manage downloading files from remote servers related to services
 */
package com.globalblue.services;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileOutputStream;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;

import com.globalblue.StartupConstants;
import com.globalblue.ftp.FTPDownloader;

public class ServiceFileDownloader {
	public static Logger logger = Logger.getLogger(ServiceFileDownloader.class);
	public static final String CONFIG_FILE = "C:\\IET_DashBoard\\config\\serverIpConfiguration.txt";

	/**
	 * Download the configuration files related to services based on the server
	 * ip list
	 * 
	 * @param serverIpList
	 */
	public void downloadFiles(List<String> serverIpList) {

		try {
			String folderPath = "";
			for (String serverIp : serverIpList) {
				List<String> serviceList = getRelatedServiceList(serverIp);

				for (String serviceName : serviceList) {
					Runtime rt = Runtime.getRuntime();
					Process p = rt.exec("sc qc \"" + serviceName + "\"");
					BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

					String line;

					do {
						line = reader.readLine();
						if (line != null && line.contains("BINARY_PATH_NAME")) {
							folderPath = line.substring(27);
							String executablePath = line.substring(29);
							folderPath = folderPath.substring(2) + ".config";
							folderPath=folderPath.replace(":", "$");
							Runtime rt1 = Runtime.getRuntime();
							p = rt1.exec("wmic /node:" + serverIp + " datafile where Name=\"" + executablePath.replace("\\", "\\\\") + "\" get Version");
							BufferedReader reader1 = new BufferedReader(new InputStreamReader(p.getInputStream()));

							String appVersion = "";
							do {
								line = reader1.readLine();
								if (line != null && line.matches(".*[0-9]+.*")) {
									appVersion = line.trim();
									break;
								}
							} while (line != null);
							String[] folderPathSplit = folderPath.split("\\\\");

							String remoteFilePath = "";
							for (int i = 2; i < folderPathSplit.length; i++) {
								remoteFilePath += "\\" + folderPathSplit[i];
							}

							String configFileName = folderPathSplit[folderPathSplit.length - 1];
							
							File source = new File("\\\\"+serverIp+"\\"+folderPath);
							File desc = new File("C:\\IET_DashBoard\\" + serverIp + "-" + serviceName + "-" + appVersion + "-" + configFileName);
							
							/*String source="\\\\"+serverIp+"\\"+folderPath;
							String desc="C:\\IET_DashBoard\\" + serverIp + "-" + serviceName + "-" + appVersion + "-" + configFileName;
							
							final String user = "uwijekoon:usw#8486@GB";
							  final NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(
							    user);
							  final SmbFile sFile = new SmbFile(desc, auth);
							  final SmbFileOutputStream smbFileOutputStream = new SmbFileOutputStream(
							    sFile);
							  final FileInputStream fileInputStream = new FileInputStream(new File(
							    source));

							  final byte[] buf = new byte[16 * 1024 * 1024];
							  int len;
							  while ((len = fileInputStream.read(buf)) > 0) {
							   smbFileOutputStream.write(buf, 0, len);
							  }
							  fileInputStream.close();
							  smbFileOutputStream.close();*/
							
							
							
							try {
							    FileUtils.copyFile(source, desc);
							} catch (IOException e) {
							    e.printStackTrace();
							}
							// rt1.exec("copy \\\\10.65.8.61\\c$\\GlobalRefund\\install.log C:\\Ureka");
							// rt1.exec("copy \\\\"+serverIp+"\\"+folderPath+" C:\\IET_DashBoard\\" + serverIp + "-" + serviceName + "-" + appVersion + "-" + configFileName);
							//FTPDownloader ftpDownloader = new FTPDownloader(serverIp, "uwijekoon", "");
							//ftpDownloader.downloadFile(remoteFilePath, "C:\\IET DashBoard\\" + serverIp + "-" + serviceName + "-" + appVersion + "-" + configFileName);
							break;
						}
					} while (line != null);
					System.out.println(folderPath);
				}
			}
		} catch (Exception e) {
			logger.log(Level.ERROR, e);
		}
	}

	/**
	 * Get the services containing words "GlobalBlue" or "GRIPS" running on the
	 * provided ip
	 * 
	 * @param ipAddress
	 * @return
	 * @throws Exception
	 */
	public List<String> getRelatedServiceList(String ipAddress) throws Exception {
		Runtime rt = Runtime.getRuntime();
		Process p = rt.exec("sc queryex type= service state= all");
		BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));

		String line;
		List<String> serviceList = new ArrayList<String>();

		do {
			line = reader.readLine();
			if (line != null && line.contains("SERVICE_NAME") && (line.contains("GlobalBlue") || line.contains("GRIPS"))) {
				serviceList.add(line.substring(14));
			}
		} while (line != null);

		int exitVal = p.waitFor();
		System.out.println("ExitValue: " + exitVal);
		return serviceList;
	}

	/**
	 * method used to get the related ip list from configuration file
	 * 
	 * @return
	 */
	public List<String> getUpdatedServerIpList() throws Exception {
		List<String> ipList = new ArrayList<>();
		try (BufferedReader br = new BufferedReader(new FileReader(CONFIG_FILE));) {
			String sCurrentLine;
			while ((sCurrentLine = br.readLine()) != null) {

				Runtime rt = Runtime.getRuntime();
				Process p = rt.exec("wmic /node:" + sCurrentLine.trim() + " os get lastBootUpTime");
				BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
				String line;
				String systemBootTime;
				do {
					line = reader.readLine();
					if (line != null && line.matches(".*[0-9]+.*")) {
						systemBootTime = line.trim().split("\\.")[0];

						SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
						Date lastBootTime = format.parse(systemBootTime);
						long diff = StartupConstants.getLastUpdatedTime().getTime() - lastBootTime.getTime();
						if (diff < 30 * 60 * 60 * 60) {
							ipList.add(sCurrentLine.trim());
						}

						break;
					}
				} while (line != null);

			}
		} catch (Exception e) {
			throw e;
		}
		return ipList;
	}

	public List<String> getAllServerIpList() throws Exception {
		List<String> ipList = new ArrayList<>();
		try (BufferedReader br = new BufferedReader(new FileReader(CONFIG_FILE));) {
			String sCurrentLine;
			while ((sCurrentLine = br.readLine()) != null) {
				ipList.add(sCurrentLine.trim());
			}
		} catch (Exception e) {
			throw e;
		}
		return ipList;
	}

	public static void main(String[] args) {
		ServiceFileDownloader downloader = new ServiceFileDownloader();
		List<String> ipList;
		try {
			ipList = downloader.getAllServerIpList();
			downloader.downloadFiles(ipList);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
}
